package com.yueban.net;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.yueban.constant.HttpConstant;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by guan on 17-8-7.
 */

public class RetrofitServiceManager {
    private static final int DEFAULT_TIME_OUT = 7;
    private static final int DEFAULT_READ_TIME_OUT = 5;
    private static RetrofitServiceManager retrofitServiceManager;
    private Retrofit mRetrofit;

    private RetrofitServiceManager() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);

        GsonBuilder gsonBuilder = new GsonBuilder();

        // Register an adapter to manage the date types as long values
        gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });

        Gson gson = gsonBuilder.create();

        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(HttpConstant.SERVER_URL)
                .build();
    }

    public static RetrofitServiceManager getInstance() {
        if (retrofitServiceManager == null)
            retrofitServiceManager = new RetrofitServiceManager();
        return retrofitServiceManager;
    }

    public <T> T create(Class<T> service) {
        return mRetrofit.create(service);
    }
}
